import fs from 'node:fs'
import path from 'node:path'

import type { ActiveConnectorType } from '@prisma/generator'
import type { MigrateTypes } from '@prisma/internals'

type CreateMigrationInput = {
  baseDir: string
  generatedMigrationName: string
}

export async function createMigration({ baseDir, generatedMigrationName }: CreateMigrationInput): Promise<string> {
  const directoryPath = path.join(baseDir, generatedMigrationName)

  if (fs.existsSync(directoryPath)) {
    throw new Error(`The migration directory already exists at ${directoryPath}`)
  }

  await fs.promises.mkdir(directoryPath, { recursive: true, mode: 0o777 })
  return directoryPath
}

type WriteMigrationScriptInput = {
  baseDir: string
  migrationName: string
  extension: string
  script: string
}

export async function writeMigrationScript({
  baseDir,
  extension,
  migrationName,
  script,
}: WriteMigrationScriptInput): Promise<void> {
  await fs.promises.writeFile(path.join(baseDir, migrationName, `migration.${extension}`), script, {
    encoding: 'utf-8',
  })
}

type WriteMigrationLockfileInput = {
  baseDir: string
  connectorType: ActiveConnectorType
  lockfile: Omit<MigrateTypes.MigrationLockfile, 'content'>
}

export async function writeMigrationLockfile({ baseDir, connectorType, lockfile }: WriteMigrationLockfileInput) {
  const lockfileContent = `# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "${connectorType}"
`
  await fs.promises.writeFile(path.join(baseDir, lockfile.path), lockfileContent, { encoding: 'utf-8' })
}
